const routes = [
  {
    path: '/user',
    element: "User",
    children: [
      { path: "/add", element: "UserAdd" },
      { path: "list", element: "UserList" },
      { path: "detail/:id", element: "UserDetail" },
    ]
  },
]

/**
 * 打平所有的路径分支并返回
 * @param {*} routes 配置对象
 * @param {*} branches 分支数组
 */
function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = '') {
  routes.forEach((route, index) => {
    let routeMeta = { // 路由的元数据
      route, // 路由对象
      relativePath: route.path || '', // 路由自己的路径
    }
    let path = joinPaths([parentPath, routeMeta.relativePath]) // path 代表访问本路由分支的路径
    // 把父路由 meta 数组加上自己的 meta 数组变成一个新数组
    let routesMeta = parentsMeta.concat(routeMeta)
    if(route.children && route.children.length > 0) {
      // 打平儿子分支 传入子路由数组 分支数组共用一个
      flattenRoutes(route.children, branches, routesMeta, path)
    }
    branches.push({
      path,
      routesMeta,
    })
  })
  return branches
}

/**
 * 将数组里面的路径合并成一个路径
 */
function joinPaths(paths) { // ['/user', '/add']
  return paths.join('/').replace(/\/\/+/g, '/') // '/user/add'
}

const branches = flattenRoutes(routes)
// console.log(branches)
console.log(JSON.stringify(branches, null, 2))
